//
//  LoverCallView.m
//  Molian
//
//  Created by 小蚕科技 on 15/6/8.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "LoverCallView.h"
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
#import "ChatSendHelper.h"



#define kRadianToDegrees(radian) (radian* 180.0 )/(M_PI)
@implementation LoverCallView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor =  RGBA(32, 36, 39, 1);
        
        //筛选的view
        [self loadMatchingView];
        //加载接通后的view
        [self loadConnectView];
        //设置接通后共有的View
        [self loadConnectMutualView];
        //加载相互喜欢后的view
        [self loadHeaderView];
        
        //加载共有的view
        [self loadMutualView];
        //加载30秒后出现的视图
          [self transferView];
        //回归初始化状态
        [self initialStatus];
        like  = NO;
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
    }
    return self;
}
-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if(message.to&&[message.to isEqualToString:[MLUser currentUser].objectId]){
        NSArray *arr = message.messageBodies;
        if (arr) {
            EMCommandMessageBody *body= message.messageBodies.lastObject;
            if (body.action && [body.action isEqualToString:ACTION_CALL_LIKE]){
                if (like) {
                      [self togetherLoveSucceed];
                }else{
                     like  = YES;
                }
               
            }
        }
    }
}
//回归初始化状态
- (void)initialStatus
{
    filtrate = 0;
    [_timeTimer invalidate];
    _timeTimer = nil;
    _timeLength = 180;
    [filtrateTimer invalidate];
    filtrateTimer = nil;
    [likeLaterTimer invalidate];
    likeLaterLength = 0;
    
    filtrateTimerView.hidden = YES;
    matchingView.hidden = NO;
    showView.hidden = YES;
    connectMutualView.hidden = YES;
    headerView.hidden = YES;
    togetherLove.hidden = NO;
    [likeBt setImage:[UIImage imageNamed:@"home_lover-call_like_icon"] withTitle:@"喜欢" forState:UIControlStateNormal];
    likeBt.userInteractionEnabled = YES;
    handsBt.selected = NO;
     dataView.frame =CGRectMake(DeviceWidth/2-80 , DeviceHeight/2-60, 160, 120);
}
//连接通话成功
- (void)connectCall
{
    matchingView.hidden = YES;
    showView.hidden = NO;
    connectMutualView.hidden = NO;
}
//完成相互喜欢
- (void)togetherLoveSucceed
{
    [ChatSendHelper sendTextMessageWithString:@"和你聊的很开心哦" toUsername:_chatUser.objectId isChatGroup:NO requireEncryption:NO ext:nil];
     [_timeTimer invalidate];
    [filtrateTimer invalidate];
    showView.hidden = YES;
    headerView.hidden = NO;
  //  [self reversalView:_headerImageView];
    
    CATransition *trans=[[CATransition alloc]init];
    [trans setType:kCATransitionReveal];
    [trans setSubtype:kCATransitionFromLeft];
    [trans setType:@"oglFlip"];
    [trans setDuration:0.5];
    [_headerImageView.layer addAnimation:trans forKey:nil];
    
//    headerView.alpha = 0;
//    [Utils Hidden:headerView Bool:YES];
    connectMutualView.hidden = NO;
    CGRect frame = dataView.frame;
    frame.origin.y = frame.origin.y+60;
    dataView.frame = frame;
  
}
- (void)reversalView:(UIView *)view
{
    //开始动画
    [UIView beginAnimations:@"doflip" context:nil];
    //设置时常
    [UIView setAnimationDuration:1];
    //设置动画淡入淡出
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    //设置代理
    [UIView setAnimationDelegate:self];
    //设置翻转方向
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft  forView:view cache:YES];
    //动画结束
    [UIView commitAnimations];
}
- (void)filtrateTimer
{
    [filtrateTimer invalidate];
    filtrateTimer = nil;
    filtrateTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(transfer) userInfo:nil repeats:YES];
}
- (void)transfer
{
    filtrate +=1;
    if (filtrate>=30) {
        filtrateTimerView.hidden = NO;
        [callTimer invalidate];
        callTimer = nil;
        filtrate = 0;
        //关闭定时器
        [filtrateTimer setFireDate:[NSDate distantFuture]];
    }
}
- (void)transferView
{
    filtrateTimerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    filtrateTimerView.backgroundColor = [UIColor clearColor];
    [self addSubview:filtrateTimerView];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(30, DeviceHeight/2-160, DeviceWidth-60, 320)];
    whiteView.layer.cornerRadius = 5;
    whiteView.layer.masksToBounds  = YES;
    whiteView.backgroundColor = [UIColor whiteColor];
    [filtrateTimerView addSubview:whiteView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(whiteView.frame.size.width/2-85, 15, 170, 170)];
    imageView.image = [UIImage imageNamed:@"home_lover-call_love-call_img"];
    [whiteView addSubview:imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 180, whiteView.frame.size.width-40, 65)];
    label.textColor = RGBA(135, 135, 135, 1);
    label.font = kFont(14);
    label.text = @"正在用力匹配中,亲爱的耐心哦。";
    label.numberOfLines = 0;
    [whiteView addSubview:label];
    
    UIButton *leftBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBt  addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    leftBt .frame = CGRectMake(0, whiteView.frame.size.height-50, whiteView.frame.size.width/2,50);
    [leftBt  setTitle:@"再等等" forState:UIControlStateNormal];
     leftBt.titleLabel.font  = kFont(18);
    [leftBt setTitleColor:RGBA(83, 83, 83, 1) forState:UIControlStateNormal];
    [whiteView addSubview:leftBt];
    
    UIButton *rightBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBt  addTarget:self action:@selector(clickRight) forControlEvents:UIControlEventTouchUpInside];
    rightBt .frame = CGRectMake(whiteView.frame.size.width/2, whiteView.frame.size.height-50, whiteView.frame.size.width/2, 50);
    [rightBt  setTitle:@"取消" forState:UIControlStateNormal];
    rightBt.titleLabel.font  = kFont(18);
    [rightBt setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
    [whiteView addSubview:rightBt];
    
    UIView *lineae = [[UIView alloc] initWithFrame:CGRectMake(0, leftBt.frame.origin.y, whiteView.frame.size.width, 0.5)];
    lineae.backgroundColor = RGBA(185, 185, 185, 1);
    [whiteView addSubview:lineae];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(whiteView.frame.size.width/2-0.25, leftBt.frame.origin.y, 0.5, 50)];
    line.backgroundColor = RGBA(185, 185, 185, 1);
    [whiteView addSubview:line];
}
- (void)clickLeft
{
    filtrateTimerView.hidden = YES;
    //开启定时器
    [filtrateTimer setFireDate:[NSDate distantPast]];
   
    //重新查找
    [self beginLoversCall];
}
- (void)clickRight
{
    [self cancelBt];
    filtrateTimerView.hidden = YES;
    
    
//    if ([self.delegate respondsToSelector:@selector(loveCallOut)]) {
//        [self.delegate loveCallOut];
//    }
}
- (void)beginLoversCall
{
    like  = NO;
    //创建随机数据(先异性匹配)
    if (!self.lovers) {
        self.lovers = [MLLovers object];
    }
    
    //男性
       self.lovers.status = MLLovers_NORMAL;
       self.lovers.user= [MLUser currentUser];
       self.lovers.gender = [MLUser currentUser].gender;
        [self.lovers saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [ShareData shareData].loversCall = YES;
                //开始随机电话
                if (self.lovers.gender == MLLoversGender_MALE) {
                    AVQuery *q = [MLLovers query];
                    [q includeKey:@"user"];
                    [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:MLLovers_NORMAL]];
                    [q whereKey:@"gender" notEqualTo:[NSNumber numberWithInteger:self.lovers.gender]];
                    [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    
                        if ( [ShareData shareData].loversCall) {
                            if (!error&&objects.count) {
                                
                                //关闭定时器
                               [filtrateTimer setFireDate:[NSDate distantFuture]];
                               
                                  int value = arc4random()%objects.count;
                                MLLovers *chatLovers = (MLLovers *)[objects objectAtIndex:value];
                                MLUser *user = (MLUser *)chatLovers.user;
                                //存在并且有数据
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"loversCallOutWithChatter" object:@{@"chatter":user.objectId, @"chatUser":user, @"type":[NSNumber numberWithInt:eCallSessionTypeVideo]}];
                            }else{
                              
                                [self callTimer];
                            }
                        }
    
                    }];
                }
            }else{
                [HUD Prompt:@"网络错误"];
            }
        }];
}
- (void)callTimer
{
    //开启定时器
    [filtrateTimer setFireDate:[NSDate distantPast]];
    [callTimer invalidate];
    callTimer = nil;
    callTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(palycall) userInfo:nil repeats:NO];
}
- (void)palycall
{
    if ([ShareData shareData].loversCall) {
        
        [self beginLoversCall];
    }
}
- (void)session:(EMCallSession *)session isIncoming:(BOOL)isIncoming ChatUser:(MLUser*)chatUser
{
    _callSession = session;
    _isIncoming = isIncoming;
    _timeLabel.text = @"";
    _timeLength = 180;
    _chatter = session.sessionChatter;
      [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    if (!chatUser) {
        AVQuery *chatUser = [MLUser query];
        [chatUser whereKey:@"objectId" equalTo:_callSession.sessionChatter];
        
        [chatUser findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            _chatUser = [objects firstObject];
            [self setChatUserData];
            
        }];
    }else{
        _chatUser = chatUser;
         [self setChatUserData];
    }
    
    
    g_callCenter = [[CTCallCenter alloc] init];
    g_callCenter.callEventHandler=^(CTCall* call)
    {
        if(call.callState == CTCallStateIncoming)
        {
            NSLog(@"Call is incoming");
             [_timeTimer invalidate];
            [filtrateTimer invalidate];
            [callTimer invalidate];
            [likeLaterTimer invalidate];
            
              [[EaseMob sharedInstance].callManager asyncEndCall:_callSession.sessionId reason:eCallReason_Hangup];
            [self _close];
        }
    };
    
    if (_isIncoming) {
        [self answerAction];
    }
}
- (void)setChatUserData
{
    _nameLabel.text = _chatUser.nickname;
    
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:_chatUser.avatar.url]];

    userLocation.text = _chatUser.location_city;
    constellation.text = [_chatUser getUserConstellation];
//    typeLabel.text = _chatUser.belong;
    CGRect frame = dataView.frame;
//    if (_chatUser.called_tags&&_chatUser.called_tags.count) {
//        userMicrophone.text = [_chatUser.called_tags firstObject];
//        microphoneLabel.hidden = NO;
//        userMicrophone.hidden = NO;
//        frame.size.height = 120;
//    }else{
        microphoneLabel.hidden = YES;
        userMicrophone.hidden = YES;
           frame.size.height = 90;
  //  }
    dataView.frame = frame;
    
}
//共有的
- (void)loadMutualView
{
    UIButton *cancelBt = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBt.frame = CGRectMake(10, 30, 40, 40);
    [cancelBt setImage:[UIImage imageNamed:@"home_lover-call_cancel_icon"] forState:UIControlStateNormal];
    [cancelBt setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 16, 16)];
    [cancelBt addTarget:self action:@selector(cancelBt) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancelBt];
    
//    //    //向上滑动的图片
//    UIImageView *swipeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(DeviceWidth/2-12, DeviceHeight-48, 24, 24)];
//    swipeImageView.image = [UIImage imageNamed:@"home_lover call_arrow_icon"];
//    [self addSubview:swipeImageView];
//    
//    UISwipeGestureRecognizer *swipeGR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGR:)];
//    swipeGR.direction = UISwipeGestureRecognizerDirectionUp;
//    [self addGestureRecognizer:swipeGR];
}
- (void)swipeGR:(UISwipeGestureRecognizer *)swipeGR
{
    if (swipeGR.direction == UISwipeGestureRecognizerDirectionUp){
        [Utils animationMobileTimer:1 View:self Rect:CGRectMake(0, -DeviceHeight, DeviceWidth, DeviceHeight)];
        
    }
}
- (void)loadMatchingView
{
    matchingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    matchingView.backgroundColor = [UIColor clearColor];
    matchingView.userInteractionEnabled = NO;
    [self addSubview:matchingView];
    
    matchingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(DeviceWidth/2-40, DeviceHeight/2-80, 80, 80)];
    NSArray *gifArray = [NSArray arrayWithObjects: [UIImage imageNamed:@"home_lover-call_-matching_icon_01"], [UIImage imageNamed:@"home_lover-call_-matching_icon_02"], [UIImage imageNamed:@"home_lover-call_-matching_icon_03"],nil];
    matchingImageView.animationImages = gifArray;
    matchingImageView.animationDuration = 1.5;
    [matchingImageView startAnimating];
    [matchingView addSubview:matchingImageView];
    UILabel *matchingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, matchingImageView.frame.origin.y+100, DeviceWidth, 20)];
    matchingLabel.text = @"努力匹配中...";
    matchingLabel.font = [UIFont fontWithName:FontName size:14];
    matchingLabel.textAlignment = NSTextAlignmentCenter;
    matchingLabel.textColor = [UIColor whiteColor];
    [matchingView addSubview:matchingLabel];
}
- (void)loadConnectView
{
    showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    showView.backgroundColor = RGBA(32, 36, 39, 1);
    showView.userInteractionEnabled = NO;
    [self addSubview:showView];
    
    countView = [[UIView alloc] initWithFrame:CGRectMake(DeviceWidth/2-110, DeviceHeight/7, 220, 60)];
    countView.backgroundColor = [UIColor clearColor];
    [showView addSubview:countView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 140, 20)];
    label.text = @"倒计时";
    label.textColor = RGBA(155, 155, 155, 1);
    label.font = kFont(13);
    [countView addSubview:label];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(label.frame.origin.x,label.frame.origin.y+25,label.frame.size.width, 40)];
    _timeLabel.font = [UIFont fontWithName:FontName size:55];
    _timeLabel.backgroundColor = [UIColor clearColor];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    [countView addSubview:_timeLabel];
}
//换人
- (void)clickSubstitutionBt
{
    //换人
    [self hangupAction];
    
}
//喜欢
- (void)clicklikeBt
{
    [likeBt setImage:[UIImage imageNamed:@"home_lover-call_like_pre_icon"] forState:UIControlStateNormal];
    togetherLove.hidden = YES;
    likeBt.userInteractionEnabled = NO;
    if (like) {
        //已经喜欢过了
        [self togetherLoveSucceed];
       // [self inquireChatStatus];
    }else{
        like = YES;
    }
    EMChatCommand *cmdChat = [[EMChatCommand alloc] init];
    cmdChat.cmd = ACTION_CALL_LIKE;
    EMCommandMessageBody *body = [[EMCommandMessageBody alloc] initWithChatObject:cmdChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver: _chatUser.objectId bodies:@[body]];
    message.messageType = eMessageTypeChat;
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
}
//- (void)inquireChatStatus
//{
//
//        
//        AVQuery *q1 = [MLDate query];
//        AVQuery *q2 = [MLDate query];
//        [q1 whereKey:@"user"  equalTo:_chatUser];
//        [q1 whereKey:@"sponsor"  equalTo:[MLUser currentUser]];
//        [q2 whereKey:@"user"  equalTo:[MLUser currentUser]];
//        [q2 whereKey:@"sponsor"  equalTo:_chatUser];
//        AVQuery *q = [AVQuery orQueryWithSubqueries:[NSArray arrayWithObjects:q1,q2,nil]];
//        [q getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
//            if (!error&&object) {
//                
//            }else{
//                MLDate *date = [MLDate object];
//                date.user = _chatUser;
//                date.sponsor = [MLUser currentUser];
//                date.status = MLDateStatus_SUCCEED;
//                [date saveInBackground];
//                // 给用户发送通话申请被同意的消息
//                NSDictionary *ext = @{@"notification": EMMESSAGE_EXT_TYPE_CALL_APPLY_ACCEPTED};
//                [ChatSendHelper sendTextMessageWithString:@"和你聊的很开心哦" toUsername:_chatUser.objectId isChatGroup:NO requireEncryption:NO ext:ext];
//            }
//        }];
//}
//免提
- (void)clickHandsBt
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if (handsBt.selected) {
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
    }else{
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    }
    [audioSession setActive:YES error:nil];
    handsBt.selected = !handsBt.selected;
}
//举报
- (void)rightItemInform
{
    HJActionSheet *sheet = [[HJActionSheet alloc]initWithTitle:nil Delegate:self destructiveButtonTitle:@"取消" OtherButtonTitles:@[@"色情狂",@"乱骂人",@"神经病",@"举报并上传截图"]];
    sheet.Delegate = self;
    [sheet show];
}
-(void)hjActionSheet:(UIButton *)sender clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSArray *arr = @[@"色情狂",@"乱骂人",@"神经病",@"举报并上传截图"];
    if (buttonIndex < arr.count) {
        NSString *str = [arr objectAtIndex:buttonIndex];
        //先查询是否举报过了
        AVQuery *query = [MLReportRecord query];
        [query whereKey:@"reportee" equalTo:_chatUser];
        [query whereKey:@"reporter" equalTo:[MLUser currentUser]];
        [query whereKey:@"status" equalTo:[NSNumber numberWithInteger:MLReportRecordStatus_NORMAL]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error&&objects.count) {
                
                // [HUD Prompt:@"你已经举报过了"];
            }else{
                
                if([str isEqualToString:@"举报并上传截图"]){
                    if ([self.delegate respondsToSelector:@selector(pushReportVCUser:)]) {
                        [self.delegate pushReportVCUser:_chatUser];
                    }
                }else{
                
                MLReportRecord *report =[MLReportRecord object];
                MLUser *u = [MLUser currentUser];
                report.reportee = _chatUser;
                report.reporter = u;
                report.remark = str;
                report.status = MLReportRecordStatus_NORMAL;
                [report saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        [AVAnalytics event:@"举报"]; // 通知服务器一个点击事件。
                        [HUD Prompt:@"举报成功"];
                        //需要发透传
                        NSDictionary *params = @{@"touserId": [MLUser currentUser].objectId,@"type":@3};
                        [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
                            
                        }];
                          NSDictionary *nparams = @{@"userId":_chatUser.objectId};
                        [AVCloud callFunctionInBackground:@"reportUser" withParameters:nparams block:^(id object, NSError *error) {
                            
                        }];
                        
                    }else{
                        [HUD Prompt:@"请返回后重试"];
                    }
                }];
                }
            }
        }];
    }
}

- (void)loadConnectMutualView
{
    connectMutualView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    connectMutualView.backgroundColor = [UIColor clearColor];
    connectMutualView.userInteractionEnabled = YES;
    [self addSubview:connectMutualView];
    
    //举报
    UIButton *rightBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBt setTitle:@"举报" forState:UIControlStateNormal];
    [rightBt addTarget:self action:@selector(rightItemInform) forControlEvents:UIControlEventTouchUpInside];
    rightBt.titleLabel.font = kFont(16);
    rightBt.frame = CGRectMake(DeviceWidth-60, 30, 60, 20);
    [connectMutualView addSubview:rightBt];
    
    //资料
    dataView =[[UIView alloc] initWithFrame:CGRectMake(DeviceWidth/2-80 , DeviceHeight/2-60, 160, 120)];
    dataView.backgroundColor = RGBA(50, 53, 56, 1);
    dataView.layer.cornerRadius = 5;
    dataView.layer.masksToBounds = YES;
    [connectMutualView addSubview:dataView];
    
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 15, 30, 16)];
    locationLabel.text = @"城市:";
    locationLabel.font = kFont(12);
    locationLabel.textColor = RGBA(162, 163, 164, 1);
    [dataView addSubview:locationLabel];
    
    userLocation = [[UILabel alloc] initWithFrame:CGRectMake(locationLabel.frame.origin.x+locationLabel.frame.size.width+5, locationLabel.frame.origin.y, 80, 16)];
    userLocation.text = @"";
    userLocation.font = kFont(14);
    userLocation.textColor = [UIColor whiteColor];
    [dataView addSubview:userLocation];
    
    UILabel *constellationLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, locationLabel.frame.origin.y+22, 30, 16)];
    constellationLabel.text = @"星座:";
    constellationLabel.font = kFont(12);
    constellationLabel.textColor = RGBA(162, 163, 164, 1);
    [dataView addSubview:constellationLabel];
    constellation = [[UILabel alloc] initWithFrame:CGRectMake(constellationLabel.frame.origin.x+constellationLabel.frame.size.width+5, constellationLabel.frame.origin.y, 80, 16)];
    constellation.text = @"";
    constellation.font = kFont(14);
    constellation.textColor = [UIColor whiteColor];
    [dataView addSubview:constellation];
    
    UILabel *typeLabelLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, constellationLabel.frame.origin.y+22, 30, 16)];
    typeLabelLabel.text = @"类型:";
    typeLabelLabel.font = kFont(12);
    typeLabelLabel.textColor = RGBA(162, 163, 164, 1);
    [dataView addSubview:typeLabelLabel];
    typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(typeLabelLabel.frame.origin.x+typeLabelLabel.frame.size.width+5, typeLabelLabel.frame.origin.y, 80, 16)];
    typeLabel.text = @"";
    typeLabel.font = kFont(14);
    typeLabel.textColor = [UIColor whiteColor];
    [dataView addSubview:typeLabel];
    
    
    
    microphoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(30,typeLabelLabel.frame.origin.y+22 , 55, 16)];
    microphoneLabel.text = @"想你叫Ta:";
    
    microphoneLabel.font = kFont(12);
    microphoneLabel.textColor = RGBA(162, 163, 164, 1);
    [dataView addSubview:microphoneLabel];
    
    userMicrophone = [[UILabel alloc] initWithFrame:CGRectMake(microphoneLabel.frame.origin.x+microphoneLabel.frame.size.width+5, microphoneLabel.frame.origin.y, 80, 16)];
    userMicrophone.text = @"";
    userMicrophone.font = kFont(14);
    userMicrophone.textColor = [UIColor whiteColor];
    
    [dataView addSubview:userMicrophone];
    
    
    //换人
    substitutionBt = [UIButtonImageWithLabel buttonWithType:UIButtonTypeCustom];
    [substitutionBt  addTarget:self action:@selector(clickSubstitutionBt) forControlEvents:UIControlEventTouchUpInside];
    substitutionBt .frame = CGRectMake((DeviceWidth-62*3)/3, DeviceHeight-125, 62, 62+26);
    [substitutionBt setImage:[UIImage imageNamed:@"home_lover-call_substitution_icon-"] withTitle:@"换人" forState:UIControlStateNormal];
    [connectMutualView addSubview:substitutionBt];
    //    //喜欢
    likeBt = [UIButtonImageWithLabel buttonWithType:UIButtonTypeCustom];
    [likeBt  addTarget:self action:@selector(clicklikeBt) forControlEvents:UIControlEventTouchUpInside];
    likeBt .frame = CGRectMake((DeviceWidth-62*3)/2+62, DeviceHeight-125, 62, 62+26);
    [likeBt setImage:[UIImage imageNamed:@"home_lover-call_like_icon"] withTitle:@"喜欢" forState:UIControlStateNormal];
    [connectMutualView addSubview:likeBt];
    
    togetherLove = [UIButton buttonWithType:UIButtonTypeCustom];
    togetherLove.frame = CGRectMake(DeviceWidth/2-46.5, likeBt.frame.origin.y-52, 93, 52);
    [togetherLove setBackgroundImage:[UIImage imageNamed:@"home_lover-call_-tooltip_img"] forState:UIControlStateNormal];
    togetherLove.titleLabel.font = [UIFont fontWithName:FontName size:12];
    togetherLove.titleLabel.numberOfLines = 2;
    [togetherLove setTitleEdgeInsets:UIEdgeInsetsMake(-5, 10, 5, 10)];
    [togetherLove setTitle:@"  双方都喜欢   就可无限通话" forState:UIControlStateNormal];
    [togetherLove setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
    [connectMutualView addSubview:togetherLove];
    
    //    //免提
    handsBt = [UIButtonImageWithLabel buttonWithType:UIButtonTypeCustom];
    [handsBt  addTarget:self action:@selector(clickHandsBt) forControlEvents:UIControlEventTouchUpInside];
    handsBt .frame = CGRectMake((DeviceWidth-62*3)/3*2+62*2, DeviceHeight-125, 62, 62+26);
    [handsBt setImage:[UIImage imageNamed:@"home_lovers-call_--hands-free_icon"] withTitle:@"免提" forState:UIControlStateNormal];
    [handsBt setImage:[UIImage imageNamed:@"home_lovers-call_--hands-free_press_icon"] forState:UIControlStateSelected];
    handsBt.selected = NO;
    [connectMutualView addSubview:handsBt];
    
}
- (void)cancelBt
{
    [ShareData shareData].loversCall = NO;
     [self initialStatus];
    [self hangupAction];
    [self.lovers deleteInBackground];
    self.lovers = [MLLovers object];
    //取消挂断电话
    self.frame =  CGRectMake(0, -DeviceHeight, DeviceWidth, DeviceHeight);
     [[UIApplication sharedApplication].delegate.window sendSubviewToBack:[ShareData shareData].loverCallView];
}
- (void)dealloc
{
    
    
    if (_timeTimer) {
        [_timeTimer invalidate];
        _timeTimer = nil;
    }
    
    
    
    if (_imageDataBuffer) {
        free(_imageDataBuffer);
        _imageDataBuffer = nil;
    }
     [[NSNotificationCenter defaultCenter] removeObserver:self];
      // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
}

#pragma mark - subviews
- (void)loadHeaderView
{
    headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.userInteractionEnabled = NO;
    [self addSubview:headerView];
    
    likeLaterLabel = [[UILabel alloc] initWithFrame:CGRectMake(DeviceWidth/2-40, 30, 80, 20)];
    likeLaterLabel.backgroundColor = [UIColor clearColor];
    likeLaterLabel.font = kFont(16);
    likeLaterLabel.textAlignment = NSTextAlignmentCenter;
    likeLaterLabel.textColor = [UIColor whiteColor];
    [headerView addSubview:likeLaterLabel];
    
    self.backgroundColor = RGBA(43, 48, 51, 1);
    CGFloat y = 120;
    if ( IS_IPHONE_4) {
        y = 80;
    }
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width - 100) / 2, y, 100, 100)];
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:_chatUser.avatar.url]];
    _headerImageView.layer.masksToBounds = YES;//开启圆角
    [_headerImageView.layer setCornerRadius:50];
    [headerView addSubview:_headerImageView];
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _headerImageView.frame.origin.y+120, DeviceWidth, 20)];
    _nameLabel.font = [UIFont fontWithName:FontName size:15];
    _nameLabel.backgroundColor = [UIColor clearColor];
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.text = _chatUser.nickname;
    [headerView addSubview:_nameLabel];
    
    
    
}
- (void)likeLaterTimerAction:(id)sender
{
    likeLaterLength += 1;
    NSInteger hour = likeLaterLength / 3600;
    m = (likeLaterLength - hour * 3600) / 60;
    s = likeLaterLength - hour * 3600 - m * 60;
    
    if (hour > 0) {
        likeLaterLabel.text = [NSString stringWithFormat:@"%.2li:%.2li:%.2li", (long)hour, (long)m, (long)s];
    }
    else if(m > 0){
        likeLaterLabel.text = [NSString stringWithFormat:@"%.2li:%.2li", (long)m, (long)s];
    }
    else{
        likeLaterLabel.text = [NSString stringWithFormat:@"00:%.2li", (long)s];
    }
}

#pragma mark - ring
- (void)timeTimerAction:(id)sender
{
    _timeLength -= 1;
    if(_timeLength<=0){
        [self hangupAction];
    }
    
    
    NSInteger hour = _timeLength / 3600;
    m = (_timeLength - hour * 3600) / 60;
    s = _timeLength - hour * 3600 - m * 60;
    
    if (hour > 0) {
        _timeLabel.text = [NSString stringWithFormat:@"%.2li:%.2li:%.2li", (long)hour, (long)m, (long)s];
    }
    else if(m > 0){
        _timeLabel.text = [NSString stringWithFormat:@"%.2li:%.2li", (long)m, (long)s];
    }
    else{
        _timeLabel.text = [NSString stringWithFormat:@"00:%.2li", (long)s];
    }
    
    
    
}
//-(void)callFunctionInBackground:(NSDictionary*)params
//{
//    [AVCloud callFunctionInBackground:@"newTransferAccount" withParameters:params block:^(id object, NSError *error) {
//        if (!error) {
//        } else {
//            [self callFunctionInBackground:params];
//        }
//    }];
//}
#pragma mark - private
//- (void)_insertMessageWithStr:(NSString *)str
//{
//    EMChatText *chatText = [[EMChatText alloc] initWithText:str];
//    EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:chatText];
//    EMMessage *message = [[EMMessage alloc] initWithReceiver:_callSession.sessionChatter bodies:@[textBody]];
//    message.isRead = YES;
//    message.isReadAcked = YES;
//    message.deliveryState = eMessageDeliveryState_Delivered;
//    [[EaseMob sharedInstance].chatManager insertMessageToDB:message append2Chat:YES];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"insertCallMessage" object:message];
//}
- (void)_close
{
    
    _callSession = nil;
    [_timeTimer invalidate];
    _timeTimer = nil;
    [callTimer invalidate];
    callTimer = nil;
    [filtrateTimer invalidate];
    [likeLaterTimer invalidate];
    likeLaterTimer = nil;
    likeLaterLength = 0;
    [self initialStatus];
    filtrate = 0;
    filtrateTimer = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hideFromViewAnimated:YES];
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        [[EaseMob sharedInstance].callManager removeDelegate:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"callControllerClose" object:nil];
      
    });
}
#pragma mark AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    if (_callSession.status != eCallSessionStatusAccepted) {
        return;
    }
}
#pragma mark - ICallManagerDelegate

- (void)callSessionStatusChanged:(EMCallSession *)callSession
                    changeReason:(EMCallStatusChangedReason)reason
                           error:(EMError *)error
{
    NSLog(@"%@",callSession.sessionId);
    if(![_callSession.sessionId isEqualToString:callSession.sessionId]){
        return;
    }
    if(error){
        //连接失败
        [self _close];
        if (error.errorCode == EMErrorCallChatterOffline) {
            AVQuery *q = [MLLovers query];
            MLUser *user = [MLUser object];
            [user setObjectId:callSession.sessionChatter];
            [q whereKey:@"user" equalTo:user];
            [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
           // [HUD Prompt:@"对方不在线"];
        }else{
            //[HUD Prompt:@"初始化失败"];
        }
       
        //连接失败,从新拨号
         [self callTimer];
        return;
    }
    
    if (callSession.status == eCallSessionStatusDisconnected) {
        NSLog(@"callSession.status == eCallSessionStatusDisconnected");
        NSString *str = @"通话结束";
        NSLog(@"%@",str);
        if(_timeLength == 180)
        {
            if (reason == eCallReason_Hangup) {
                str = @"取消通话";
            }
            else if (reason == eCallReason_Reject||reason == eCallReason_Offline){
                str = @"拒接通话或不在线";
                //,删除相关数据.
                AVQuery *q = [MLLovers query];
                MLUser *user = [MLUser object];
                [user setObjectId:callSession.sessionChatter];
                [q whereKey:@"user" equalTo:user];
                [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    
                }];
            }
            else if (reason == eCallReason_Busy){
                str = @"正在通话中";
            }
        }
      //  [HUD Prompt:str];
        //        [self _insertMessageWithStr:str];

          [self _close];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([ShareData shareData].loversCall) {
                [self beginLoversCall];
            }
        });
    }
    else if (callSession.status == eCallSessionStatusAccepted)
    {
        self.lovers.status = MLLovers_Call;
        [self.lovers saveInBackground];
        
        [self connectCall];
        //通话中
        _timeLength = 180;
        [self timeTimerAction:nil];
        _timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeTimerAction:) userInfo:nil repeats:YES];
        
        likeLaterLength = 0;
        likeLaterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(likeLaterTimerAction:) userInfo:nil repeats:YES];
        
        if(!_isIncoming)
        {
            NSLog(@"我呼出去被接通");
        }
    }
}
- (void)hangupAction
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:_audioCategory error:nil];
    [audioSession setActive:YES error:nil];
    
    [[EaseMob sharedInstance].callManager asyncEndCall:_callSession.sessionId reason:eCallReason_Hangup];
}
#pragma mark - action
//接听
- (void)answerAction
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    _audioCategory = audioSession.category;
    if(![_audioCategory isEqualToString:AVAudioSessionCategoryPlayAndRecord]){
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [audioSession setActive:YES error:nil];
    }
    
    [[EaseMob sharedInstance].callManager asyncAnswerCall:_callSession.sessionId];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
